package com.magicborrow.fragment;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.ListView;

import com.magicborrow.R;
import com.magicborrow.adapter.SearchHistoryAdapter;
import com.magicborrow.utils.SearchHistoryUtils;
import java.util.ArrayList;

/**
 * Created by River on 5/14/16.
 */
public class SearachHistoryFragment extends Fragment{

    private LinearLayout mFragmentLayout;
    private ListView mListView;
    private ArrayList<String> searchHitory;
    OnlineSelectedListener mCallback;
    SearchHistoryAdapter adapter;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        mFragmentLayout = (LinearLayout)inflater.inflate(R.layout.search_history_pop,null);
        initView();
        initData();
        return mFragmentLayout;
    }

    public interface OnlineSelectedListener {
        void onlineSelected(String content);
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        Activity activity;
        if(context instanceof Activity){
            activity = (Activity)context;
            try {
                mCallback = (OnlineSelectedListener) activity;
            } catch (ClassCastException e) {
                throw new ClassCastException(activity.toString()
                        + " must implement OnHeadlineSelectedListener");
            }
        }
    }

    private void initView(){
        mListView = (ListView)mFragmentLayout.findViewById(R.id.listView);
    }

    private void initData(){
        searchHitory = SearchHistoryUtils.getSearchHistory(getActivity());
        if(searchHitory != null){
           final View view = LayoutInflater.from(getActivity()).inflate(R.layout.history_search_footview,null);
            (view.findViewById(R.id.clear)).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    searchHitory.clear();
                    adapter.notifyDataSetChanged();
                    mListView.removeFooterView(view);
                    SearchHistoryUtils.saveSearchHistory(getActivity(),null);
                }
            });
            mListView.addFooterView(view);
            adapter = new SearchHistoryAdapter(getActivity());
            adapter.setData(searchHitory);
            mListView.setAdapter(adapter);
        }
        mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                mCallback.onlineSelected(searchHitory.get(position));
            }
        });
    }

}
